//
//  HMEmoticonToolBar.swift
//  MicroBlog
//
//  Created by Apple on 16/10/6.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
//toolBar按钮的枚举类型
enum HMEmoticonToolBarButtonType: Int {
    //最近
    case recent = 1
    //默认
    case normal = 2
    //Emoji
    case emoji = 3
    //浪小花
    case lxh = 4
}
//自定义表情键盘的toolBar
class HMEmoticonToolBar: UIStackView {

    //记录上次选中的按钮
    var lastSelectedbutton: UIButton?
    //点击按钮执行的闭包
    var callBack: ((HMEmoticonToolBarButtonType) -> ())?
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //布局方式
        axis = .horizontal
        //填充方式
        distribution = .fillEqually
        addChildButton(title: "最近", imageName: "compose_emotion_table_left", type: .recent)
        addChildButton(title: "默认", imageName: "compose_emotion_table_mid", type: .normal)
        addChildButton(title: "Emoji", imageName: "compose_emotion_table_mid", type: .emoji)
        addChildButton(title: "浪小花", imageName: "compose_emotion_table_right", type: .lxh)
    }

    //添加子按钮的方法
    private func addChildButton(title: String, imageName: String, type: HMEmoticonToolBarButtonType) {
        let button = UIButton()
        //枚举值作为tag
        button.tag = type.rawValue
        button.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
        button.setTitle(title, for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .selected)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.setBackgroundImage(UIImage(named: imageName + "_normal"), for: .normal)
        button.setBackgroundImage(UIImage(named: imageName + "_selected"), for: .selected)
        button.adjustsImageWhenHighlighted = false
        //添加按钮
        addArrangedSubview(button)
        if type == .normal {
            lastSelectedbutton?.isSelected = false
            button.isSelected = true
            lastSelectedbutton = button
        }
    }
    
    //点击事件
    @objc private func btnAction(btn: UIButton) {
        //设置相同按钮不同重复点击
        if lastSelectedbutton == btn {
            return
        }
        lastSelectedbutton?.isSelected = false
        btn.isSelected = true
        lastSelectedbutton = btn
        //根据枚举的原始值初始化枚举
        let type = HMEmoticonToolBarButtonType(rawValue: btn.tag)!
        //执行闭包
        callBack?(type)
    }
    
    //根据组数的索引选中响应的按钮
    func selectedButton(section: Int) {
        //使用tag=0 表示取到的是当前视图自己
        let button = viewWithTag(section + 1) as! UIButton
        if lastSelectedbutton == button {
            return
        }
        lastSelectedbutton?.isSelected = false
        button.isSelected = true
        lastSelectedbutton = button
    }
}
